package com.springboot.cloud.common.core.pay;

import com.github.wxpay.sdk.WXPayUtil;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.GsonBuilder;
import com.lly835.bestpay.config.AliPayConfig;
import com.lly835.bestpay.config.WxPayConfig;
import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.service.impl.alipay.AliPayServiceImpl;
import lombok.extern.slf4j.Slf4j;
import okhttp3.logging.HttpLoggingInterceptor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class WeiXinPayService {
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private WxPayConfig wxPayConfig;

    public WeiXinPayService() {
    }

    public void setWxPayConfig(WxPayConfig wxPayConfig) {
        this.wxPayConfig = wxPayConfig;
    }

    public Map wxPaybill(PayRequest request) {
        //组装参数，用户生成统一下单接口的签名
        Map<String, Object> packageParams = new HashMap<>();
        // 业务参数
        packageParams.put("out_trade_no", request.getOrderId());
        packageParams.put("total_fee", new BigDecimal(request.getOrderAmount()).multiply(new BigDecimal(100)).intValue() + "");
        //生成的随机字符串
        String nonce_str = WXPayUtil.generateNonceStr();
        packageParams.put("appid", wxPayConfig.getAppAppId());
        packageParams.put("mch_id", wxPayConfig.getMchId());
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("body", "会员充值");
            packageParams.put("spbill_create_ip", "0.0.0.0");
        packageParams.put("notify_url", wxPayConfig.getNotifyUrl());//支付成功后的回调地址
        packageParams.put("trade_type", "APP");//支付方式

        String prestr = PayUtil.createLinkString(packageParams); // 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串

        //MD5运算生成签名，这里是第一次签名，用于调用统一下单接口
        String sign = PayUtil.sign(prestr, wxPayConfig.getMchKey(), "utf-8").toUpperCase();

        //拼接统一下单接口使用的xml数据，要将上一步生成的签名一起拼接进去
        packageParams.put("sign", sign);
        log.info("【微信统一支付】发起支付,packageParams:{}", packageParams);
        String xml = MapXmlUtil.map2Xmlstring(packageParams);
        //调用统一下单接口，并接受返回的结果

        log.info("【微信统一支付】发起支付,xml:{}", xml);
        String result = PayUtil.httpRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", xml);
        log.info("【微信统一支付】发起支付,返回结果:{}", result);

        if (StringUtils.isEmpty(result)) {
            throw new RuntimeException("【微信统一支付】发起支付, 网络异常");
        }

        // 将解析结果存储在HashMap中
        Map map = MapXmlUtil.xmlString2Map(result);
        String return_code = (String) map.get("return_code");//返回状态码
        Map<String, Object> data = new HashMap<>();//返回给小程序端需要的参数
        String prepay_id = (String) map.get("prepay_id");//返回的预付单信息
        log.info("【微信统一支付】发起支付,return_code:{}", return_code);
        if ("SUCCESS".equals(return_code)) {
            //app的返回值
            data.put("appid", wxPayConfig.getAppAppId());
            data.put("partnerid", wxPayConfig.getMchId());
            data.put("prepayid", prepay_id);
            data.put("noncestr", nonce_str);
            Long timeStamp = System.currentTimeMillis() / 1000;
            data.put("timestamp", timeStamp + "");
            data.put("package", "Sign=WXPay");
            String stringSignTemp = PayUtil.createLinkString(data);
            String appSign = PayUtil.sign(stringSignTemp, wxPayConfig.getMchKey(), "utf-8").toUpperCase();
            data.put("sign", appSign);
            log.info("【微信统一支付】返回前端:{}", data);
        }
        return data;
    }
}
